package org.adorsys.aderp.aderplogin.roles;

import java.util.Collection;

import org.springframework.expression.EvaluationContext;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.security.access.AccessDecisionVoter;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.expression.ExpressionUtils;
import org.springframework.security.access.expression.SecurityExpressionHandler;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.FilterInvocation;

public class ContextualWebExpressionVoter implements AccessDecisionVoter<FilterInvocation>  {

    private SecurityExpressionHandler<FilterInvocation> expressionHandler = new ContextualWebSecurityExpressionHandler();
	
    private SpelExpressionParser expressionParser = new SpelExpressionParser();
    
	@Override
	public boolean supports(ConfigAttribute attribute) {
		return ContextualWebExpressionConfigAttribute.isWebExpressionConfigAttribute(attribute);
	}

	@Override
	public boolean supports(Class<?> clazz) {
        return true;
	}

	@Override
    public int vote(Authentication authentication, FilterInvocation fi, Collection<ConfigAttribute> attributes) {
        assert authentication != null;
        assert fi != null;
        assert attributes != null;

        ContextualWebExpressionConfigAttribute weca = findConfigAttribute(attributes);

        if (weca == null) {
            return ACCESS_ABSTAIN;
        }

        EvaluationContext ctx = expressionHandler.createEvaluationContext(authentication, fi);

        return ExpressionUtils.evaluateAsBoolean(weca.getAuthorizeExpression(), ctx) ?
                ACCESS_GRANTED : ACCESS_DENIED;
    }

    private ContextualWebExpressionConfigAttribute findConfigAttribute(Collection<ConfigAttribute> attributes) {
        for (ConfigAttribute attribute : attributes) {
            if (ContextualWebExpressionConfigAttribute.isWebExpressionConfigAttribute(attribute)) {
                return ContextualWebExpressionConfigAttribute.newInstance(attribute,expressionParser);
            }
        }
        return null;
    }


    public void setExpressionHandler(SecurityExpressionHandler<FilterInvocation> expressionHandler) {
        this.expressionHandler = expressionHandler;
    }
}
